/**
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import {
	doUserInfo
} from '@/apis/user.js'
import {
	defineStore
} from 'pinia'
import qqMap from '@/utils/qqMap.js'

export const useAppsStore = defineStore('app', {
	state: () => ({
		token: '',
		userInfo: {
			balance: 100,
		},
		location: {
			cityName: '',
			longitude: '',
			latitude: ''
		},
		pid: ''
	}),
	getters: {
		getPid: state => state.pid,
		getToken: state => state.token,
		getUserInfo: state => state.userInfo,
		getCityName: state => state.location.cityName,
	},
	actions: {
		setPid(pid) {
			this.pid = pid
		},
		setCityname(name) {
			this.location.cityName = name
		},
		async setLocation(res) {
			const params = {
				latitude: res.latitude,
				longitude: res.longitude,
				cityName: res?.cityName || ''
			}
			if (!params?.cityName && params.latitude) {
				const result = await qqMap.reverseGeocoder(params.latitude, params.longitude)
				params.cityName = result.result.address_component.city
			}
			this.location = params
			return this.location
		},
		/**
		 * @description 获取用户信息
		 * @param matched
		 * @returns
		 */
		async doUserInfo() {
			const {
				code,
				data,
				message
			} = await doUserInfo()
			if (code !== 200) {
				signOut()
				throw message
			}
			this.userInfo = data
		},
		/**
		 * @description 设置token
		 * @param matched
		 * @returns
		 */
		async setToken(token) {
			this.token = token
			const {
				code,
				data,
				message
			} = await doUserInfo()
			if (code !== 200) {
				signOut()
				throw message
			}
			this.userInfo = data
			uni.setStorageSync('token', token);
			return data
		},
		/**
		 * @description 登出
		 * */
		signOut() {
			this.token = ''
			uni.reLaunch({
				url: '/pagesA/login/login'
			})
			this.userInfo = {}
		}
	}
})